﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace CookieTokenDemo.Web.Controllers;

public class AccountController : Controller
{
    [AllowAnonymous]
    public IActionResult Login()
    {
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> TestLogin()
    {
        var claims = new Claim[]
        {
            new Claim(ClaimTypes.Name, "TestUser"),
        };

        var claimsIdentity = new ClaimsIdentity(claims, "Login");

        Response.Cookies.Append("x-access-token", GenerateToken(claims), new CookieOptions()
        {
            Path = "/",
            HttpOnly = true
        });

        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));

        return Ok();
    }

    private string GenerateToken(Claim[] claims)
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SymmetricSecurityKey"));

        var token = new JwtSecurityToken(
          issuer: "http://localhost:5000",
          audience: "http://localhost:5001",
          claims: claims,
          notBefore: DateTime.Now,
          expires: DateTime.Now.AddMinutes(5),
          signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
        );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}